package handler

import (
	"encoding/json"
	"github.com/keepfoo/minirest/logger"
	"io/ioutil"
	"net/http"
)

func RestHandler(f func(args map[string]interface{}) map[string]interface{}) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		if data, err := ioutil.ReadAll(r.Body); err != nil {
			logger.Error("请求参数有问题: " + err.Error())
			w.WriteHeader(http.StatusBadRequest)
			return
		} else {
			logger.Infof("RequestURI: %s, body: %s", r.RequestURI, string(data))
			var bodyMap map[string]interface{}
			if err := json.Unmarshal(data, &bodyMap); err != nil {
				logger.Error("请求体 JSON 格式有问题: " + err.Error())
				w.WriteHeader(http.StatusBadRequest)
				return
			}
			respMap := f(bodyMap)
			w.WriteHeader(respMap["code"].(int))
			if respBody, err := json.Marshal(respMap); err != nil {
				w.WriteHeader(http.StatusInternalServerError)
			} else {
				logger.Debugf("返回数据 %s", string(respBody))
				if _, err = w.Write(respBody); err != nil {
					w.WriteHeader(http.StatusInternalServerError)
				}
			}
		}
	}
}

func RenderJson(w http.ResponseWriter, data interface{}) {
	if respBody, err := json.Marshal(data); err != nil {
		w.WriteHeader(http.StatusInternalServerError)
	} else {
		logger.Debugf("返回数据 %s", string(respBody))
		if _, err = w.Write(respBody); err != nil {
			w.WriteHeader(http.StatusInternalServerError)
		}
	}
}
